package cn.wolfcode.service.impl;

import cn.wolfcode.domain.*;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.query.TravelQuery;
import cn.wolfcode.range.FindRange;
import cn.wolfcode.repository.TravelRepository;
import cn.wolfcode.service.IDestinationService;
import cn.wolfcode.service.ITravelService;
import cn.wolfcode.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private TravelRepository travelRepository;
    @Autowired
    private MongoTemplate template;
    @Autowired
    private ITravelService travelService;
    @Autowired
    private IDestinationService destinationService;

    @Override
    public void insert(Travel travel) {
        travelRepository.save(travel);
    }

    @Override
    public void update(Travel travel) {
        travelRepository.save(travel);
    }

    @Override
    public void delete(String id) {
        travelRepository.deleteById(id);
    }

    @Override
    public Travel get(String id) {
        Travel travel = travelRepository.findById(id).orElse(null);
        if (travel!=null) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
            Destination destination = destinationService.get(travel.getDestId());
            travel.setDest(destination);
        }
        return travel;
    }

    @Override
    public List<Travel> listAll() {
        return travelRepository.findAll();
    }

    @Override
    public Page query(TravelQuery qo) {
        //创建查询对象
        Query query = new Query();
        //查询总条数
        long count = template.count(query, Travel.class);
        if (count == 0){
            return Page.empty();
        }

        if (StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        if (qo.getState()==Travel.STATE_WAITING){
            query.addCriteria(Criteria.where("state").is(qo.getState()));
        }
        if (qo.getState()==Travel.STATE_REJECT){
            query.addCriteria(Criteria.where("state").is(qo.getState()));
        }
        //出行时间
        FindRange day = qo.getDay();
        if (day != null){
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lte(day.getMax()));
        }
        //花费
        FindRange ex = qo.getPerExpend();
        if (ex != null){
            query.addCriteria(Criteria.where("perExpend").gte(ex.getMin()).lte(ex.getMax()));
        }
        Pageable page = null;
        if (qo.getOrderType() == 1){
            page = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.DESC,"createTime");
        }else if(qo.getOrderType() == 2){
            page = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.DESC,"viewnum");
        }else {//兜底
            page = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        }

        query.with(page);
        List<Travel> list = template.find(query, Travel.class);
        Page<Travel> pageable = new PageImpl<>(list, page, count);
        for (Travel travel : pageable) {
            UserInfo userInfo = userInfoService.get(travel.getUserId());
            travel.setAuthor(userInfo);
        }

        return pageable;
    }

    @Override
    public void changeAudit(String id,int state) {
        //查出游记对象
        Travel travel = travelService.get(id);
        if (!StringUtils.hasLength(id)) {
            throw new LogicException("参数异常");
        }
        //状态不为待审核状态就不可以通过或者拒绝
        /*if (travel.getState()!=Travel.STATE_WAITING) {
            throw new LogicException("不允许审核");
        }*/
        //若是修改状态为通过审核状态
        if (state==Travel.STATE_RELEASE){
            //修改状态为通过审核状态
            travel.setState(Travel.STATE_RELEASE);
            //修改发布时间 最后更新时间
            travel.setCreateTime(new Date());
            travel.setReleaseTime(new Date());
            travelService.update(travel);
        }else if (state==Travel.STATE_REJECT){//若是修改状态为拒绝审核状态
            //修改状态为拒绝状态
            travel.setState(Travel.STATE_REJECT);
            //设置最后更新时间为null
            travel.setLastUpdateTime(null);
            travelService.update(travel);
        }else if(state==Travel.STATE_WAITING){//下架
            travel.setState(state);
            travel.setCreateTime(null);
            travel.setLastUpdateTime(null);
            travelService.update(travel);
        } else {
            throw new LogicException("状态不为待审核状态");
        }

    }

    @Override
    public void saveOrUpdate(Travel travel,UserInfo user) {
        //添加目的地名称 destName
        Destination dest = destinationService.get(travel.getDestId());
        travel.setDestName(dest.getName());
        //添加用户id userId
        travel.setUserId(user.getId());
        //添加最后更新时间 lastUpdateTime
        travel.setLastUpdateTime(new Date());

        if (StringUtils.hasLength(travel.getId())){
            travelService.update(travel);
        }else {
            travel.setCreateTime(new Date());
            travelService.insert(travel);
        }
    }

    @Override
    public List<Travel> viewnumTop3(String destId) {
        Pageable pageable = PageRequest.of(0,3, Sort.Direction.DESC,"viewnum");
        List<Travel> list = travelRepository.findByDestId(destId, pageable);
        return list;
    }

    @Override
    public List<Travel> queryByDestName(String keyword) {
        List<Travel> ts = travelRepository.queryByDestName(keyword);
        for (Travel t : ts) {
            t.setAuthor(userInfoService.get(t.getUserId()));
            t.setDest(destinationService.get(t.getDestId()));
        }
        return ts;
    }


}
